#!/bin/bash

set -e

#
# Pushes smartcontract/explorer:circleci to relevant location based on passed args:
# push_explorer <branch> <gittag>
# ie:
# push_explorer '' explorer-v0.6.9          -> 0.6.9 and latest
# push_explorer release/explorer-0.6.9 ''   -> candidate-0.6.9
#
# Ignores anything not matching above.
#
# Key assumption: local version of smartcontract/explorer:circleci is the image
# to work with.
#

if [ -z "$DOCKERHUB_PASS" ]
then
  echo "Cannot push to dockerhub, credentials are missing."
  exit 1
fi


circle_branch="$1"
circle_tag="$2"

PROJECT_ROOT=`git rev-parse --show-toplevel`
pushd $PROJECT_ROOT >/dev/null

tag_and_push() {
  # ie: docker tag and push smartcontract/explorer:0.9.1, since DOCKER_TAG=0.9.1
  export DOCKER_TAG=$1
  (set -x; docker tag smartcontract/explorer:circleci smartcontract/explorer:${DOCKER_TAG})
  pushd explorer
  make dockerpush
  popd
}

branch=`tools/ci/branch2tag ${circle_branch}`
version_tag=`tools/ci/gittag2dockertag ${circle_tag}`

# version tag takes precedence.
if [ -n "${version_tag}" ]; then
  if [[ "${circle_tag}" =~ ^explorer-v([a-zA-Z0-9.]+) ]]; then
    echo "Publishing full release of Explorer ${version_tag}"
    tag_and_push "$version_tag"
    tag_and_push latest
  else
    echo "Not publishing for this '${circle_tag}'."
  fi
elif [ -n "$branch" ]; then
  # Only if we're on explorer branch
  if [[ "${circle_branch}" =~ ^release(s)?\/explorer-(.+)$ ]]; then
    echo "Publishing candidate release of Explorer ${version_tag}"
    tag_and_push "$branch"
  else
    echo "Not publishing for ${circle_branch}."
  fi
else
  echo "Not publishing for '${circle_tag}/${circle_branch}'."
fi
